package com.carrot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Maps;
import com.carrot.common.constant.UserConstants;
import com.carrot.common.core.domain.dto.SysStationDto;
import com.carrot.common.core.domain.entity.SysStation;
import com.carrot.common.enums.OnlineEnableEnum;
import com.carrot.common.exception.ServiceException;
import com.carrot.common.mybatis.BaseServiceImpl;
import com.carrot.common.utils.StringUtils;
import com.carrot.system.mapper.*;
import com.carrot.system.service.ISysStationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 场站 业务层处理
 *
 * @author liuhongzhen
 */
@Service
public class SysStationServiceImpl extends BaseServiceImpl<SysStationMapper, SysStation>
        implements ISysStationService {

    private static final Logger log = LoggerFactory.getLogger(SysStationServiceImpl.class);

    @Resource
    private SysStationMapper stationMapper;

    /**
     * 通过场站ID查询场站
     *
     * @param stationId 场站ID
     * @return 场站对象信息
     */
    @Override
    public SysStation selectStationByStationId(String stationId) {
        return stationMapper.selectStationByStationId(stationId);
    }

    /**
     * 校验场站名称是否唯一
     *
     * @param station 场站信息
     * @return 结果
     */
    @Override
    public boolean checkStationNameUnique(SysStation station) {
        String stationName =
                StringUtils.isNull(station.getStationName()) ? "" : station.getStationName();
        SysStation info = stationMapper.checkStationIdUnique(station.getStationName());
        if (StringUtils.isNotNull(info) && info.getStationName().equals(stationName)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验场站名称是否唯一
     *
     * @param station 场站信息
     * @return 结果
     */
    @Override
    public boolean checkStationIdUnique(SysStation station) {
        String stationId = StringUtils.isNull(station.getStationId()) ? "" : station.getStationId();
        SysStation info = stationMapper.checkStationIdUnique(station.getStationId());
        if (StringUtils.isNotNull(info) && info.getStationId().equals(stationId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 电池组和单体的关系
     */
    @Override
    public Map<Integer, Integer> getCellPackMap(String stationId) {

        SysStation station = this.query()
                .eq("station_id", stationId)
                .one();

        Integer packNum = station.getPackNum();
        Integer cellNum = station.getCellNum();

        if (null == packNum || 0 == packNum || null == cellNum || 0 == cellNum) {
            throw new ServiceException("电池组和单体数配置有问题！");
        }

        //校验下单体数和电池组
        if (cellNum % packNum != 0) {
            throw new ServiceException("单体数必须是电池组数的整倍数！");
        }

        int packCellNum = cellNum / packNum;
        int cellNo = 1;
        Map<Integer, Integer> cellPackMap = Maps.newHashMap();
        for (int pack = 1; pack <= packNum; pack++) {
            for (int j = 0; j < packCellNum; j++) {
                cellPackMap.put(cellNo, pack);
                cellNo += 1;
            }
        }

        return cellPackMap;
    }

    /**
     * 新增保存场站信息
     *
     * @param station 场站信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public int insertStation(SysStation station) {

        // 判断stationId是否唯一
        SysStation sysStation1 = this.query().eq("station_id", station.getStationId()).one();
        if (null != sysStation1) {
            throw new ServiceException("场站ID:" + station.getStationId() + "已存在");
        }

        SysStation sysStation2 = this.query().eq("station_name", station.getStationName()).one();
        if (null != sysStation2) {
            throw new ServiceException("场站名称:" + station.getStationName() + "已存在");
        }

        SysStation sysStation3 = this.query().eq("station_alias", station.getStationAlias()).one();
        if (null != sysStation3) {
            throw new ServiceException("场站别名:" + station.getStationAlias() + "已存在");
        }

        int clusterNum = station.getClusterNum();
        int packNum = station.getPackNum();
        int cellNum = station.getCellNum();

        if (cellNum % packNum != 0) {
            throw new ServiceException("单体数必须是电池组数的整倍数！");
        }

        if (cellNum % clusterNum != 0) {
            throw new ServiceException("单体数必须是电池簇数的整倍数！");
        }

        this.save(station);
        return 1;
    }

    /**
     * 修改保存场站信息
     *
     * @param station 场站信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public int updateStation(SysStation station) {

        SysStation sysStation = this.getById(station.getId());

        if (StringUtils.isNotEmpty(station.getStationId()) &&
                !sysStation.getStationId().equals(station.getStationId())) {
            SysStation sysStation1 = this.query().eq("station_id", station.getStationId()).one();
            if (null != sysStation1) {
                throw new ServiceException("场站ID:" + station.getStationId() + "已存在");
            }
        }

        if (StringUtils.isNotEmpty(station.getStationName()) &&
                !sysStation.getStationName().equals(station.getStationName())) {
            SysStation sysStation1 = this.query().eq("station_name", station.getStationName()).one();
            if (null != sysStation1) {
                throw new ServiceException("场站名称:" + station.getStationName() + "已存在");
            }
        }

        if (StringUtils.isNotEmpty(station.getStationAlias()) &&
                !sysStation.getStationAlias().equals(station.getStationAlias())) {
            SysStation sysStation1 = this.query().eq("station_alias", station.getStationAlias()).one();
            if (null != sysStation1) {
                throw new ServiceException("场站别名:" + station.getStationAlias() + "已存在");
            }
        }

        int clusterNum = station.getClusterNum();
        int packNum = station.getPackNum();
        int cellNum = station.getCellNum();

        if (cellNum % packNum != 0) {
            throw new ServiceException("单体数必须是电池组数的整倍数！");
        }

        if (cellNum % clusterNum != 0) {
            throw new ServiceException("单体数必须是电池簇数的整倍数！");
        }

        UpdateWrapper<SysStation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", station.getId());
        this.update(station, updateWrapper);
        return 1;
    }

    /**
     * 通过场站ID删除场站
     *
     * @param id 场站ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public int deleteStationById(Long id) {
        SysStation station = this.getById(id);
        if (null == station) {
            throw new ServiceException("不存在该数据记录");
        }
        if (station.getEnable().equals(OnlineEnableEnum.ENABLE.getValue())) {
            throw new ServiceException("启用状态的场站不可以删除");
        }
        this.removeById(id);
        return 1;
    }

    /**
     * 批量删除场站信息
     *
     * @param ids 需要删除的场站ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public int deleteStationByIds(List<Long> ids) {

        SysStation station =
                this.query().in("id", ids)
                        .eq("enable", OnlineEnableEnum.ENABLE.getValue())
                        .one();

        if (station.getEnable().equals(OnlineEnableEnum.ENABLE.getValue())) {
            throw new ServiceException("启用状态的场站不可以删除");
        }
        this.removeBatchByIds(ids);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void changeStatus(SysStationDto dto) {
        SysStation station = this.getById(dto.getId());
        if (null == station) {
            throw new ServiceException("不存在该数据记录");
        }
        UpdateWrapper<SysStation> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", dto.getId());
        updateWrapper.set("enable", dto.getEnable());
        this.update(updateWrapper);
    }
}
